<template>
  <div class="project-info-container">
    <el-card class="project-card" shadow="hover">
      <div class="header">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon"><Document /></el-icon>
            项目信息
            <el-tag v-if="projectId" type="primary" size="small" style="margin-left: 10px;">
              项目ID: {{ projectId }}
            </el-tag>
          </h2>
          <p class="description">
            查看和编辑项目的基本信息，包括项目名称、编号、负责人、时间等详细信息
          </p>
        </div>
        <div class="action-buttons">
          <el-button v-if="!isEditing" type="primary" @click="startEdit" :disabled="!projectData">
            <el-icon><Edit /></el-icon>
            编辑信息
          </el-button>
          <template v-else>
            <el-button @click="cancelEdit">
              <el-icon><Close /></el-icon>
              取消
            </el-button>
            <el-button type="primary" @click="saveProject" :loading="saveLoading">
              <el-icon><Check /></el-icon>
              保存
            </el-button>
          </template>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-section">
        <el-skeleton :rows="8" animated />
      </div>

      <!-- 项目信息展示 -->
      <div v-else-if="projectData && !isEditing" class="info-display">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目编号">
            <el-tag type="info">{{ projectData.project_id }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="项目名称">
            <span class="project-name">{{ projectData.project_name }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="项目地点">
            {{ projectData.project_location }}
          </el-descriptions-item>
          <el-descriptions-item label="项目经理">
            <el-tag type="success">{{ getUserNameById(projectData.project_manager) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="项目状态">
            <el-tag :type="getStateTagType(projectData.state)" size="small">
              {{ projectData.state }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(projectData.create_time) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDate(projectData.update_time) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            <div class="remark-content">
              {{ projectData.remark || '暂无备注信息' }}
            </div>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 快速操作区域 -->
        <div class="quick-actions">
          <h3 class="section-title">
            <el-icon><Operation /></el-icon>
            快速操作
          </h3>
          <div class="action-grid">
            <el-button type="primary" @click="goToPage('stakeholder')">
              <el-icon><User /></el-icon>
              干系人管理
            </el-button>
            <el-button type="success" @click="goToPage('status')">
              <el-icon><DataBoard /></el-icon>
              项目状态
            </el-button>
            <el-button type="warning" @click="goToPage('timeline')">
              <el-icon><Calendar /></el-icon>
              实施周期
            </el-button>
            <el-button type="info" @click="goToPage('change')">
              <el-icon><Refresh /></el-icon>
              变更记录
            </el-button>
            <el-button type="primary" @click="goToPage('milestone')">
              <el-icon><Flag /></el-icon>
              节点计划
            </el-button>
            <el-button type="success" @click="goToPage('experience')">
              <el-icon><Document /></el-icon>
              经验总结
            </el-button>
            <el-button type="warning" @click="goToPage('human')">
              <el-icon><UserFilled /></el-icon>
              人力资源
            </el-button>
            <el-button type="danger" @click="goToPage('issue')">
              <el-icon><Warning /></el-icon>
              问题汇总
            </el-button>
            <el-button type="info" @click="goToPage('document')">
              <el-icon><Folder /></el-icon>
              资料管理
            </el-button>
            <el-button type="primary" @click="goToPage('weight')">
              <el-icon><TrendCharts /></el-icon>
              权重设置
            </el-button>
          </div>
        </div>
      </div>

      <!-- 编辑表单 -->
      <div v-else-if="projectData && isEditing" class="edit-form">
        <el-form :model="editForm" :rules="formRules" ref="formRef" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目编号" prop="project_id">
                <el-input v-model="editForm.project_id" placeholder="请输入项目编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目名称" prop="project_name">
                <el-input v-model="editForm.project_name" placeholder="请输入项目名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目地点" prop="project_location">
                <el-input v-model="editForm.project_location" placeholder="请输入项目地点" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目经理" prop="project_manager">
                <el-select v-model="editForm.project_manager" placeholder="请选择项目经理" style="width: 100%">
                  <el-option
                    v-for="user in userList"
                    :key="user.id"
                    :label="user.Username"
                    :value="user.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目状态" prop="state">
                <el-select v-model="editForm.state" placeholder="请选择项目状态" style="width: 100%">
                  <el-option label="计划中" value="计划中" />
                  <el-option label="进行中" value="进行中" />
                  <el-option label="已完成" value="已完成" />
                  <el-option label="暂停" value="暂停" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目总工时" prop="total_hours">
                <el-input v-model="editForm.total_hours" placeholder="请输入项目总工时" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注" prop="remark">
            <el-input 
              v-model="editForm.remark" 
              type="textarea" 
              :rows="4" 
              placeholder="项目备注信息（选填）" 
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 无数据状态 -->
      <div v-else class="no-data">
        <el-empty description="未找到项目信息">
          <el-button type="primary" @click="$router.push('/project/list')">
            返回项目列表
          </el-button>
        </el-empty>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Document, Edit, Close, Check, Operation, User, DataBoard, 
  Calendar, Refresh, Flag, UserFilled, Warning, Folder, TrendCharts 
} from '@element-plus/icons-vue'
import { getProjectById, updateProject } from '../../api/project'
import { getUserList } from '../../api/user'

const route = useRoute()
const router = useRouter()

const projectId = ref(route.params.id)
const projectData = ref(null)
const userList = ref([])
const loading = ref(false)
const saveLoading = ref(false)
const isEditing = ref(false)
const formRef = ref()

const editForm = ref({
  project_id: '',
  project_name: '',
  project_location: '',
  project_manager: '',
  total_hours: '',
  state: '',
  remark: ''
})

const formRules = {
  project_id: [{ required: true, message: '请输入项目编号', trigger: 'blur' }],
  project_name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  project_location: [{ required: true, message: '请输入项目地点', trigger: 'blur' }],
  project_manager: [{ required: true, message: '请选择项目经理', trigger: 'change' }],
  total_hours: [{ required: true, message: '请输入项目总工时', trigger: 'blur' }],
  state: [{ required: true, message: '请选择项目状态', trigger: 'change' }]
}

// 获取状态标签类型
function getStateTagType(state) {
  const stateMap = {
    '计划中': 'info',
    '进行中': 'primary',
    '已完成': 'success',
    '暂停': 'warning'
  }
  return stateMap[state] || 'info'
}

// 根据ID获取用户名
function getUserNameById(id) {
  const user = userList.value.find(u => u.id === id)
  return user ? user.Username : id
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 加载项目信息
async function loadProjectInfo() {
  if (!projectId.value) return
  
  loading.value = true
  try {
    const res = await getProjectById(projectId.value)
    projectData.value = res.data
  } catch (error) {
    ElMessage.error('加载项目信息失败')
    console.error('加载项目信息失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载用户列表
async function loadUsers() {
  try {
    const res = await getUserList()
    userList.value = res.data.records || []
  } catch (error) {
    console.error('加载用户列表失败:', error)
  }
}

// 开始编辑
function startEdit() {
  editForm.value = { ...projectData.value }
  isEditing.value = true
}

// 取消编辑
function cancelEdit() {
  isEditing.value = false
  editForm.value = {
    project_id: '',
    project_name: '',
    project_location: '',
    project_manager: '',
    state: '',
    remark: ''
  }
}

// 保存项目
async function saveProject() {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    saveLoading.value = true
    try {
      await updateProject(projectId.value, editForm.value)
      ElMessage.success('项目信息更新成功')
      isEditing.value = false
      await loadProjectInfo() // 重新加载数据
    } catch (error) {
      ElMessage.error('更新失败，请重试')
      console.error('更新失败:', error)
    } finally {
      saveLoading.value = false
    }
  })
}

// 跳转到其他页面
function goToPage(pageType) {
  if (!projectId.value) {
    ElMessage.warning('请先选择项目')
    return
  }
  
  const pageMap = {
    'stakeholder': 'stakeholder',
    'status': 'status',
    'timeline': 'timeline',
    'change': 'change',
    'milestone': 'milestone',
    'experience': 'experience',
    'human': 'human',
    'issue': 'issue',
    'document': 'document',
    'weight': 'weight'
  }
  
  const targetPage = pageMap[pageType]
  if (targetPage) {
    router.push(`/project/${targetPage}/${projectId.value}`)
  }
}

onMounted(() => {
  loadProjectInfo()
  loadUsers()
})
</script>

<style scoped>
.project-info-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.project-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.title-section {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  font-size: 24px;
  color: #67c23a;
}

.description {
  margin: 0;
  font-size: 14px;
  color: #909399;
  line-height: 1.5;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.loading-section {
  padding: 40px 0;
}

.info-display {
  margin-bottom: 30px;
}

.project-name {
  font-weight: 600;
  color: #303133;
  font-size: 16px;
}

.remark-content {
  color: #606266;
  line-height: 1.6;
  white-space: pre-wrap;
}

.quick-actions {
  margin-top: 30px;
  padding-top: 30px;
  border-top: 1px solid #ebeef5;
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.edit-form {
  max-width: 800px;
}

.no-data {
  padding: 60px 0;
  text-align: center;
}

:deep(.el-descriptions) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  background: #f5f7fa;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
}

@media (max-width: 768px) {
  .project-info-container {
    padding: 10px;
  }
  
  .header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .action-buttons {
    justify-content: flex-end;
  }
  
  .action-grid {
    grid-template-columns: 1fr;
  }
}
</style> 